define([
  'jquery',
  'jqueryui',
  'underscore',
  'backbone',
  'lightboxme',  
  'msgbox',
  'text!templates/refer/referPatientTemplate.html'
], function($,JQueryUI, _, Backbone,LightBoxMe,MsgBox,referPatientTemplate){

  var ReferPatientView = Backbone.View.extend({
    el: $(".mainpanel"),
    initialize: function(){
    	var ReferModel = Backbone.Model.extend({url:'/referPatient'});
    	this.model = new ReferModel();
    },
    events: {
    	'click #searchRefer' : 'referButton'
    	} ,
    render: function(){
    	var self=this;
    	  this.$el.html(referPatientTemplate);
          $("input#patientName").autocomplete({
        	  source: function(request,response){
	    			 $.ajax({
	    			        type: "GET",
	    			        url: "/getPatientName?term="+$("input#patientName").val(),
	    			        success: function(data){
	    			              response($.map(data, function(item) {
	    			                    return { 
	    			                        label: item.name + " - "+ item.provider ,
	    			                        value: item.name,
	    			                        id: item.id,
	    			                        userid: item.userid,
	    			                        provider: item.provider,
	    			                        phoneNo: item.phoneNumber,
	    			                        email: item.email
	    			                        };
	    			                    }));
	    			        }
	    		    });
	    	    } , 
      	    minLength: 2,
      	    select: function(e,ui){
      	    	$("input#patientName").attr("userid",ui.item.id);
      		    switch(ui.item.provider){
  		    	case "google":
  		    		$("#patientImg").attr("src","https://profiles.google.com/s2/photos/profile/"+ui.item.userid);
  		    		break;
  		    	case "facebook":
  		    		$("#patientImg").attr("src","https://graph.facebook.com/"+ui.item.userid+"/picture");
  		    		break;
  		    	case "twitter":
  		    		$("#patientImg").attr("src","https://api.twitter.com/1/users/profile_image?user_id="+ui.item.userid);
  		    		break;
  		    }
      		    
      		  $("#patientPhone").val(ui.item.phoneNo);
      		  $("#patientEmail").val(ui.item.email);

      	    }/*,
      	    change: function(e,ui){
      	    	$("input#patientName").attr("userid",null);
      	    }*/
      	});
     
  	    $("#referredDoctorName").multiselect({
  	    	noneSelectedText: "Select Doctor",
  	    	multiple: false,
  		   selectedList: 1,
  		 click: function(event, ui){
  		    var provider=$('#referredDoctorName').find(":selected").attr("provider");
  		    switch(provider){
  		    	case "google":
  		    		$("#doctorImg").attr("src","https://profiles.google.com/s2/photos/profile/"+$('#referredDoctorName').find(":selected").attr("userid"));
  		    		break;
  		    	case "facebook":
  		    		$("#doctorImg").attr("src","https://graph.facebook.com/"+$('#referredDoctorName').find(":selected").attr("userid")+"/picture");
  		    		break;
  		    	case "twitter":
  		    		$("#doctorImg").attr("src","https://api.twitter.com/1/users/profile_image?user_id="+$('#referredDoctorName').find(":selected").attr("userid"));
  		    		break;
  		    }
  		    
  		  $.ajax({
  	        type: "GET",
  	        url: "/getDoctorsHospitals/"+ui.value,
  	        success: function(response){
  	        	$('#selectReferredHospital').empty();
  	        	$.each(response, function (i, item) {
  	        	    $('#selectReferredHospital').append($('<option>', { 
  	        	        value: item.hospitals.id,
  	        	        text : item.hospitals.hospitalName
  	        	    }));
  	        	});
  	        	renderApp();
  	        }
  	    });
		  var renderApp = _.after(2, function(){
		         //  	        	$("#selectReferredHospital").multiselect('refresh');
		  	        	$(".dnone").removeClass("dnone");
		  	          $("#selectProblem").multiselect({
		  	  	    	noneSelectedText: "Patient Problems",
		  	  	    	multiple: false,
		  	  	    	selectedList: 1
		  	  	    	}).multiselectfilter();
		  	      
		  	  	    $("#selectReferredHospital").multiselect({
		  	  	    	noneSelectedText: "Select Hospital",
		  	  	    	multiple: false,
		  	  		   selectedList: 1
		  	    	}).multiselectfilter();

		        });

  		  $.ajax({
    	        type: "GET",
    	        url: "/doctorsreferralTemplates/"+ui.value,
    	        success: function(response){
    	        	$('#selectProblem').empty();
    	        	$.each(response, function (i, item) {
    	        	    $('#selectProblem').append($('<option>', { 
    	        	        value: item.id,
    	        	        text : item.topicName
    	        	    }));
    	        	});
    	        	renderApp();
    	        }
    	    });
  		    
  		   }
    	}).multiselectfilter();
  	    
  	  $.ajax({
	        type: "GET",
	        url: "/getDoctors",
	        success: function(response){
	        	$.each(response, function (i, item) {
	        	    $('#referredDoctorName').append($('<option>', { 
	        	        value: item.id,
	        	        text : item.name,
	        	        userid:item.userid,
	        	        provider:item.provider
	        	    }));
	        	});
	        	$("#referredDoctorName").multiselect('refresh');
	        }
	    });

    },
    referButton: function(){
    	if(!$("#patientName").attr("userid") && (!$("#patientEmail").val() || !$("#patientPhone").val())){
    		$.msgBox({
			    title:"Appment",
			    content:"The Patient Name seems to be a new patient in our system. We will appreciate if you can provide the email and phone number.",
			    type:"info",
			    success: function (result) {}
			});
    		return false;
    	}
    	if(!$("#referredDoctorName").find(":selected").attr("value")){
    		$.msgBox({
			    title:"Appment",
			    content:"Please select the doctor to refer to.",
			    type:"info",
			    success: function (result) {}
			});
    		return false;
    	}
    	

    	this.model.set("patientId",$("#patientName").attr("userid"));
    	this.model.set("patientName",$("#patientName").val());
    	this.model.set("patientPhone",$("#patientPhone").val());
    	this.model.set("patientEmail",$("#patientEmail").val());
    	this.model.set("referredDoctorId",$("#referredDoctorName").find(":selected").attr("value"));
    	this.model.set("referredDoctorHospitalId",$("#selectReferredHospital").find(":selected").attr("value"));
    	this.model.set("referredForProblem",$("#selectProblem").find(":selected").attr("value"));
    	this.model.set("referredProblemDesc",$("#selectProblem").find(":selected").text());
    	this.model.set("comments",$("#otherdetails").val());
    	this.model.save(null, {
		    success: function (model, response) {
	      		 $.msgBox({
				    title:"Appment",
				    content:"Thank you for using Appment to refer the patients! We will provide the best care for your patient.",
				    type:"info",
				    success: function (result) {}
				});

		    },
		    error: function (model, response) {
		        console.log("error");
		    }
		});
    }
  });

  return ReferPatientView;
});
